package com.base.library.permission

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationManagerCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.base.library.BaseApplication
import com.base.library.R
import com.permissionx.guolindev.PermissionMediator
import com.permissionx.guolindev.PermissionX
import com.permissionx.guolindev.callback.RequestCallback

object PermissionUtils {
    private val PERMISSION_STORAGE_GROUP = mutableListOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
    )

    /**
     * 是否有存储权限
     */
    fun hasStoragePermission(): Boolean {
        return hasPermissions(PERMISSION_STORAGE_GROUP)
    }

    fun hasPermissions(permissions: Collection<String>): Boolean {
        for (permission in permissions) {
            val hasPermission = PermissionX.isGranted(BaseApplication.context, permission)
            if (!hasPermission) {
                return false
            }
        }
        return true
    }

    fun hasPermission(permission: String): Boolean {
        return PermissionX.isGranted(BaseApplication.context, permission)
    }

    /**
     * 请求存储权限
     */
    fun requestStoragePermission(context: FragmentActivity, callback: RequestCallback?) {
        val hasStoragePermission = hasStoragePermission()
        if (!hasStoragePermission){
            showPermissionTipDialog(context, context.getString(R.string.str_storage_permission), context.getString(R.string.str_storage_permission_content))
        }
        PermissionX.init(context).requestPermissions(PERMISSION_STORAGE_GROUP, callback)
    }
    /**
     * 请求存储权限
     */
    fun requestPermission(context: FragmentActivity, permission : List<String>, callback: RequestCallback?) {
        PermissionX.init(context).requestPermissions(permission, callback)
    }

    private fun showPermissionTipDialog(context: Activity, title: String, content: String) {
        var dialog = PermissionTipDialogFragment()
        var bundle = Bundle()
        bundle.putString("title", title)
        bundle.putString("content", content)
        dialog.arguments = bundle
        dialog.show((context as AppCompatActivity).supportFragmentManager, title)
    }

    /**
     * 请求存储权限
     */
    fun Fragment.requestStoragePermission(callback: RequestCallback?) {
        val hasStoragePermission = hasStoragePermission()
        if (!hasStoragePermission){
            showPermissionTipDialog(requireActivity(), getString(R.string.str_storage_permission), getString(R.string.str_storage_permission_content))
        }
        PermissionX.init(this).requestPermissions(PERMISSION_STORAGE_GROUP, callback)
    }

    private fun PermissionMediator.requestPermission(
        permission: String, callback: RequestCallback?
    ) {
        requestPermissions(listOf(permission), callback)
    }

    private fun PermissionMediator.requestPermissions(
        permissions: List<String>, callback: RequestCallback?
    ) {
        permissions(permissions).request(callback)
    }


    /**
     * 通知权限
     */
    fun FragmentActivity.requestNotificationPermission() {
        PermissionX.init(this)
            .permissions(PermissionX.permission.POST_NOTIFICATIONS)
            .onExplainRequestReason { scope, deniedList ->
                val message = "为了保证你能及时收到消息，我们需要获取通知权限"
                scope.showRequestReasonDialog(deniedList, message, "允许", "禁止")
            }.request(null)
    }

    fun showNoticeSetting(context: Context) {
        val enabled = NotificationManagerCompat.from(context).areNotificationsEnabled()
        if (!enabled) {
            AlertDialog.Builder(context).setTitle(context.getString(R.string.str_notice_permission))
                .setMessage(context.getString(R.string.str_notice_permission_content) + "\n\n是否立即设置")
                .setPositiveButton("立即设置") { dialog, which ->
                    try {
                        goToSetting(context)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    dialog.dismiss()
                }
                .setNegativeButton("取消") { dialog, which ->
                    dialog.dismiss()
                }
                .show()
                .setCanceledOnTouchOutside(false)
        }
    }

    private fun goToSetting(context: Context) {
        try {
            val intent = Intent()
            ///< 直接跳转到应用通知设置的代码
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                Build.VERSION.SDK_INT < Build.VERSION_CODES.O
            ) {
                intent.action = "android.settings.APP_NOTIFICATION_SETTINGS"
                intent.putExtra("app_package", context.packageName)
                intent.putExtra("app_uid", context.applicationInfo.uid)
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                intent.addCategory(Intent.CATEGORY_DEFAULT)
                intent.data = Uri.parse("package:" + context.packageName)
            } else {
                ///< 4.4以下没有从app跳转到应用通知设置页面的Action，可考虑跳转到应用详情页面,
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                if (Build.VERSION.SDK_INT >= 9) {
                    intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                    intent.data = Uri.fromParts("package", context.packageName, null)
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent.action = Intent.ACTION_VIEW
                    intent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
                    intent.putExtra("com.android.settings.ApplicationPkgName", context.packageName)
                }
            }
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}